﻿#include "stdafx.h"
#include"MessagePro.h"
#include<iostream>
using namespace std;
//处理网络消息
MessagePro::MessagePro()
{
	flag = false;
	this->m_strServerip = "127.0.0.1";
	this->m_port = 8080;
}

MessagePro::MessagePro(CString m_strServerip, int m_port)
{
	flag = false;
	this->m_strServerip = m_strServerip;
	this->m_port = m_port;
}

MessagePro::~MessagePro()
{
	if (flag) {
		m_pSock->Close();
		delete m_pSock;
	}
}

bool MessagePro::Init()
{
	AfxSocketInit();
	m_pSock = new CClientSocket();
	if (!m_pSock->Create())
	{
		AfxMessageBox(_T("创建套接字失败！"));

		delete m_pSock;
		getchar();
		return false;
	}
	if (!m_pSock->Connect(m_strServerip, m_port))
	{
		AfxMessageBox(_T("连接服务器失败！"));
		delete m_pSock;
		getchar();
		return false;
	}
	flag = true;
	return true;
}

bool MessagePro::SendMsg(const char *buf)
{
	this->m_pSock->Send(buf, strlen(buf));
	return true;
}


/*解码 服务端传来的消息，
*将所有的successful ！！转换为success
*同时去除时间
*
*/
void MessagePro::simpleConvert(string & str)
{
	if (str.find("successful") != -1||str.find("Database change to")!=-1) {
		str = "success";
		return;
	}
	int pos = str.rfind(" sec");
	if ( pos!= -1) {
		str = str.substr(0, str.rfind("\r\n", pos));
		return;
	}

}


bool MessagePro::ReceiveMsg(string &str)
{
	char pData[1024] = { 0 };
	if (m_pSock->Receive(pData, 1024, 0) != SOCKET_ERROR)
	{
		string temp = pData;
		string output, msg;
		bool isSelect = false;
		while (temp.substr(0, 1) == "1") {
			output = temp.substr(1, 1023);
			if (output.substr(0, 6) == "select") {
				isSelect = true;
				output = output.substr(7, 1017);
			}
			memset(pData, 0, 1024);
			m_pSock->Receive(pData, 1024, 0);
			temp = pData;
			msg += output;
		}

		///*
		output = temp.substr(1, 1023);
		if (output.substr(0, 6) == "select") {
			msg = output.substr(7, 1017);
		}
		else if (isSelect) {
			msg += output;
		}
		else {
			str = output;
			simpleConvert(str);
			return true;
		}
		str = msg;
		simpleConvert(str);
		return true;
	}
	return false;
}


